package br.com.abella.snippets.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.SocketChannel;

/**
 * NonBlockingSocket
 * 
 * @author Daniel Abella
 *
 */
public class NonBlockingSocket {

	public static void main(String[] args) throws IOException {
		
		ServerSocket server = new ServerSocket();
		
		SocketChannel socketChannel = server.createSocketChannel("127.0.0.1", 6002);
		
		while(!socketChannel.finishConnect()) {
			System.out.printf("connection not established yet.");
		}
		
		System.out.printf("connection established.");
	}
}

/**
 * Server Socket
 * 
 * @author Daniel Abella
 *
 */
class ServerSocket {

	private SocketChannel socketChannel;
	
	/**
	 * Create an not blocking SocketChannel (Java NIO). 
	 * 
	 * @param hostName
	 * @param port
	 * @return
	 */
	public SocketChannel createSocketChannel(String host, int port) {

		try {

			socketChannel = SocketChannel.open(); //create socketChannel

			socketChannel.configureBlocking(false); //not blocking socket

			/* InetSocketAddress provides an immutable object used by sockets for binding, connecting, or as returned values. */

			SocketAddress address = new InetSocketAddress(host, port);

			socketChannel.connect(address); //not blocking call

		} catch (IOException e) {
			socketChannel = null;
			e.printStackTrace();
		}

		return socketChannel;
	}
	
	/**
	 * 
	 * Close SocketChannel. If there is no opend connection, IllegalStateException is throwed.
	 * 
	 * @throws IllegalStateException
	 */
	public void closeSocketChannel() throws IllegalStateException {
		
		if (socketChannel == null)
			throw new IllegalStateException("SocketChannel cannot be closed because there is no opened connecion.");
		
		try {
			socketChannel.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
} //serversocket-end
